import pygame
import sys
import math
from player import Player
from enemy import Enemy
from level import Level
from start_screen import StartScreen
from sound_manager import SoundManager
from config import *

# 初始化Pygame
pygame.init()

# 游戏窗口设置
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("战斗闯关游戏")

# 时钟对象
clock = pygame.time.Clock()

# 创建音效管理器
sound_manager = SoundManager()

class Camera:
    def __init__(self, width, height):
        self.camera = pygame.Rect(0, 0, width, height)
        self.width = width
        self.height = height
        self.x = 0
        self.y = 0
        
    def apply(self, entity):
        # 应用摄像机偏移
        if hasattr(entity, 'rect'):
            return entity.rect.move(self.camera.x, self.camera.y)
        return entity.move(self.camera.x, self.camera.y)
        
    def update(self, target):
        # 更新摄像机位置，跟随目标
        self.x = -target.rect.centerx + SCREEN_WIDTH // 2
        self.y = -target.rect.centery + SCREEN_HEIGHT // 2
        
        # 限制摄像机在世界边界内
        self.x = min(0, self.x)  # 左边界
        self.x = max(-(WORLD_WIDTH - SCREEN_WIDTH), self.x)  # 右边界
        
        self.camera = pygame.Rect(self.x, self.y, self.width, self.height)

def main():
    # 创建启动界面
    start_screen = StartScreen(screen)
    
    # 游戏状态
    game_state = "start_screen"  # "start_screen" 或 "playing"
    
    # 游戏主循环
    running = True
    while running:
        if game_state == "start_screen":
            # 处理启动界面事件
            action = start_screen.handle_events()
            if action == "start_game":
                # 初始化游戏对象
                player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
                current_level = Level(1, screen)
                camera = Camera(WORLD_WIDTH, SCREEN_HEIGHT)
                game_state = "playing"
            
            # 更新启动界面
            start_screen.update()
            
            # 绘制启动界面
            start_screen.draw()
            pygame.display.flip()
            clock.tick(FPS)
            
        elif game_state == "playing":
            # 处理游戏事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        player.jump()
                        sound_manager.play_sound("jump")
                    elif event.key == pygame.K_j:
                        player.attack()
                        sound_manager.play_sound("attack")
            
            # 获取按键状态
            keys = pygame.key.get_pressed()
            dx, dy = 0, 0
            if keys[pygame.K_a]:
                dx -= PLAYER_SPEED
            if keys[pygame.K_d]:
                dx += PLAYER_SPEED
                
            if dx != 0:
                player.move(dx, dy)
            
            # 更新游戏对象
            player.update(current_level.platforms)
            current_level.update(player)
            
            # 更新摄像机
            camera.update(player)
            
            # 检查碰撞
            current_level.check_collisions(player)
            
            # 检查胜利条件
            victory = current_level.check_victory(player)
            
            # 绘制游戏对象
            screen.fill(BLACK)
            current_level.draw(screen, camera)
            player.draw(screen, camera)
            
            # 检查玩家是否死亡
            if not player.alive:
                # 显示游戏结束界面
                # 使用系统字体解决中文乱码问题
                try:
                    # 尝试使用系统中文字体
                    game_over_font = start_screen.get_chinese_font(72)
                    restart_font = start_screen.get_chinese_font(36)
                except:
                    # 如果无法获取系统字体，使用默认字体
                    game_over_font = pygame.font.Font(None, 72)
                    restart_font = pygame.font.Font(None, 36)
                
                game_over_text = game_over_font.render("游戏结束", True, RED)
                text_rect = game_over_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
                screen.blit(game_over_text, text_rect)
                
                # 显示重新开始提示
                restart_text = restart_font.render("按 R 键重新开始，按 M 键返回菜单", True, WHITE)
                restart_rect = restart_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 60))
                screen.blit(restart_text, restart_rect)
                
                # 检查按键
                if keys[pygame.K_r]:
                    # 重新开始游戏
                    player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
                    current_level = Level(1, screen)
                    camera = Camera(WORLD_WIDTH, SCREEN_HEIGHT)
                elif keys[pygame.K_m]:
                    # 返回菜单
                    game_state = "start_screen"
            
            # 检查胜利条件
            elif victory:
                # 显示胜利界面
                # 使用系统字体解决中文乱码问题
                try:
                    # 尝试使用系统中文字体
                    victory_font = start_screen.get_chinese_font(72)
                    menu_font = start_screen.get_chinese_font(36)
                except:
                    # 如果无法获取系统字体，使用默认字体
                    victory_font = pygame.font.Font(None, 72)
                    menu_font = pygame.font.Font(None, 36)
                
                victory_text = victory_font.render("恭喜胜利！", True, GOLD)
                text_rect = victory_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
                screen.blit(victory_text, text_rect)
                
                # 显示返回菜单提示
                menu_text = menu_font.render("按 M 键返回菜单", True, WHITE)
                menu_rect = menu_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 60))
                screen.blit(menu_text, menu_rect)
                
                # 检查返回菜单按键
                if keys[pygame.K_m]:
                    # 返回菜单
                    game_state = "start_screen"
            
            # 更新显示
            pygame.display.flip()
            
            # 控制帧率
            clock.tick(FPS)
    
    # 退出游戏
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()